package com.yanqu.road.server.manger.activity.carptrip;

import com.yanqu.road.dao.impl.activity.carptrip.CarpTripConfigDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.carptrip.CarpTripConfig;
import com.yanqu.road.entity.activity.carptrip.config.*;
import com.yanqu.road.entity.activity.carptrip.enums.eCarpTripCellType;
import com.yanqu.road.entity.activity.carptrip.enums.eCarpTripEventType;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.pb.activity.CarpTripProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.carptrip.CarpTripModule;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class CarpTripMgr extends TempMgr {

    
    static CarpTripConfig config;

    static List<CarpTripProto.CarpTripBossRewardTemp> bossRewardTempList = new ArrayList<>();

    public static ActivityInfo getActivityInfo() {
        if(config == null) {
            return null;
        }
        return config.getActivityInfo();
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    public static void reloadActivityData() {
        getLogger().info("reload CarpTrip Activity start");
        ActivityInfo tempActivityInfo;
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.CarpTripActivity.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no CarpTrip Activity in show time");
            config = null;
        }else {
            List<CarpTripProto.CarpTripBossRewardTemp> bossRewardTemps = new ArrayList<>();
            tempActivityInfo = openActivityInfoList.get(0);
            int tmpActivityId = tempActivityInfo.getActivityId();

            CarpTripConfig configTemp  = new CarpTripConfig();
            configTemp.setActivityInfo(tempActivityInfo);

            //初始化配置
            //config配置
            Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityId);
            //先解析boss配置
            configTemp.setBossExParamList(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.CARPTRIP_TOWER_BOSS_EXPARAM.getName()).getValue(), "\\|"));

            CarpTripConfigDaoImpl configDao = new CarpTripConfigDaoImpl();
            List<CarpTripLevelInfo> levelInfoList = configDao.getCarpTripLevelInfoList(tmpActivityId);
            List<CarpTripTemplateInfo> templateInfoList = configDao.getCarpTripTemplateInfoList(tmpActivityId);
            List<CarpTripAbilityInfo> towerInfoList = new CarpTripConfigDaoImpl().getCarpTripInfoList(tmpActivityId);
            configTemp.setTowerInfoList(towerInfoList);

            int totalCellNum = 0;  //总层数
            int bossTimes = 0;     //boss出现次数
            //临时
            //阶段翻转配置
            List<Integer> overturnList = new ArrayList<>();
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_TOWER_MIRROR.getName())){
                overturnList = StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.CARPTRIP_TOWER_MIRROR.getName()).getValue(), "\\|");
                configTemp.setOverturnList(overturnList);
            }
            //层类型翻转映射
            int[] cellTypeReverseList = new int[]{0, 1, 2, 4, 3, 5};
            for (int passIdIndex = 0; passIdIndex < levelInfoList.size(); passIdIndex++) {
                CarpTripLevelInfo levelInfo = levelInfoList.get(passIdIndex);
                if(levelInfo.getBossId() > 0){
                    bossTimes++;
                }
                CarpTripTemplateInfo templateInfo = configTemp.getCarpTripTemplateInfo(templateInfoList, levelInfo.getTemplateId());
                if(templateInfo == null){
                    getLogger().info("CarpTrip Activity {} template {} not found", tmpActivityId, levelInfo.getId());
                    return;
                }
                levelInfo.setTemplateInfo(templateInfo);
                List<Integer> codeA = StringUtils.stringToIntegerList(templateInfo.getCodeA(), "\\|");
                if(templateInfo.getEventList().size() != codeA.size() || templateInfo.getPicList().size() != codeA.size()){
                    getLogger().info("CarpTrip Activity {} levelInfo {} config error", tmpActivityId, levelInfo.getId());
                    return;
                }
                //该层是否需要翻转
                boolean needOverTurn = false;
                if(overturnList.size() > passIdIndex && overturnList.get(passIdIndex) == 1){
                    needOverTurn = true;
                }
                if(needOverTurn){
                    List<Integer> tempCodeA = new ArrayList<>();
                    for (int i = 0; i < codeA.size(); i++) {
                        tempCodeA.add(cellTypeReverseList[codeA.get(i)]);
                    }
                    codeA = tempCodeA;
                }
                levelInfo.setCellTypeList(codeA);
                for (int cellIdx = 0; cellIdx < templateInfo.getEventList().size(); cellIdx++) {
                    String event = templateInfo.getEventList().get(cellIdx);
                    List<String> cellEventString = StringUtils.stringToStringList(event, ";");
                    if(needOverTurn){
                        Collections.reverse(cellEventString);
                    }
                    //每层事件个数校验
                    int cellType = levelInfo.getCellTypeList().get(cellIdx);
                    int eventNum = eCarpTripCellType.getEventNum(cellType);
                    if(eventNum != cellEventString.size()){
                        getLogger().info("CarpTrip Activity {} levelInfo {}  template {} config event error", tmpActivityId, levelInfo.getId(), templateInfo.getId());
                        return;
                    }
                    //形象校验
                    String pic = templateInfo.getPicList().get(cellIdx);
                    List<Integer> eventPicList = StringUtils.stringToIntegerList(pic, ";");
                    if(eventNum > eventPicList.size()){
                        getLogger().info("CarpTrip Activity {} levelInfo {}  template {} config pic error", tmpActivityId, levelInfo.getId(), templateInfo.getId());
                        return;
                    }
                    if(needOverTurn){
                        Collections.reverse(eventPicList);
                    }
                    CarpTripCell cell = new CarpTripCell();
                    cell.setPassId(levelInfo.getId());
                    cell.setCellType(cellType);
                    cell.setCellNum(++totalCellNum);
                    CarpTripAbilityInfo towerInfo = configTemp.getCarpTripInfo(cell.getCellNum());
                    for (int k = 0; k < cellEventString.size(); k++) {
                        String eventString = cellEventString.get(k);
                        List<String> eventConfig = StringUtils.stringToStringList(eventString, "=");
                        CarpTripCellEvent cellEvent = new CarpTripCellEvent();
                        cellEvent.setEventType(Integer.valueOf(eventConfig.get(0)));
                        if(cellEvent.getEventType() == eCarpTripEventType.Division.getType() || cellEvent.getEventType() == eCarpTripEventType.Treasures.getType()
                                || cellEvent.getEventType() == eCarpTripEventType.Box.getType()){
                            cellEvent.setEventVal(eventConfig.get(1));
                        }else {
                            cellEvent.setEventVal(new BigDecimal(towerInfo.getAbility()).multiply(new BigDecimal(eventConfig.get(1))).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).toString());
                        }
                        //本阶段最后一层
                        if(levelInfo.getBossId() > 0 && cellIdx == templateInfo.getEventList().size() - 1 && cellEvent.getEventType() == eCarpTripEventType.Monster.getType()){
                            if(StringUtils.isNullOrEmpty(levelInfo.getReward()) || "0".equals(levelInfo.getReward())){
                                getLogger().info("CarpTrip Activity {} levelInfo {}  boss reward is empty", tmpActivityId, levelInfo.getId());
                                return;
                            }
                            cellEvent.setEventType(eCarpTripEventType.Boss.getType());
                            cellEvent.setReward(levelInfo.getReward());
                            if(configTemp.getBossExParamList().size() > bossTimes) {
                                //血量重新计算
                                cellEvent.setEventVal(new BigDecimal(1000 + configTemp.getBossExParamList().get(bossTimes)).multiply(new BigDecimal(towerInfo.getAbility())).multiply(new BigDecimal(eventConfig.get(1))).divide(BigDecimal.valueOf(1000 * 1000), 0, BigDecimal.ROUND_UP).toString());
                            }
                            bossRewardTemps.add(CarpTripProto.CarpTripBossRewardTemp.newBuilder().setCellNum(cell.getCellNum()).setReward(levelInfo.getReward()).setBossId(levelInfo.getBossId()).build());
                        }
                        cellEvent.setPic(eventPicList.get(k));
                        cellEvent.setRawVal(Integer.valueOf(eventConfig.get(1)));
                        cell.getEventList().add(cellEvent);
                    }
                    levelInfo.getCellList().add(cell);
                }
            }

            configTemp.setLevelInfoList(levelInfoList);
            configTemp.setTemplateInfoList(templateInfoList);

            List<CarpTripRoleInfo> roleInfoList = configDao.getCarpTripRoleInfoList(tmpActivityId);
            configTemp.setRoleInfoList(roleInfoList);
            configTemp.setDragonUpInfoList(configDao.getCarpTripDragonUpInfoList(tmpActivityId));
            configTemp.setDrawUpInfoList(configDao.getCarpTripDrawUpInfoList(tmpActivityId));
            configTemp.setEventInfoList(configDao.getCarpTripEventInfoList(tmpActivityId));
            configTemp.setPvpTopList(configDao.getCarpTripPvpTopInfoList(tmpActivityId));
            configTemp.setPicInfoList(configDao.getCarpTripPicInfoList(tmpActivityId));

            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_ITEM_ID.getName())) {
                configTemp.setScoreItemId(activityConfigMap.get(eActivityConfigType.CARPTRIP_ITEM_ID.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName())){
                configTemp.setScoreItemId(activityConfigMap.get(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName()).getIntValue());
            }
            configTemp.setAuraMax(activityConfigMap.get(eActivityConfigType.CARPTRIP_AURA_MAX.getName()).getIntValue());
            configTemp.setAuraGetCd(activityConfigMap.get(eActivityConfigType.CARPTRIP_AURA_GET_CD.getName()).getIntValue());
            configTemp.setAuraGetNum(activityConfigMap.get(eActivityConfigType.CARPTRIP_AURA_GET_NUM.getName()).getIntValue());
            //configTemp.setAuraCostNum(activityConfigMap.get(eActivityConfigType.CARPTRIP_AURA_COST_NUM.getName()).getIntValue());
            configTemp.setPlayerStrengthBegin(activityConfigMap.get(eActivityConfigType.CARPTRIP_PLAYER_STRENGTH_BEGIN.getName()).getIntValue());
            configTemp.setDrawScoreBase(activityConfigMap.get(eActivityConfigType.CARPTRIP_DRAW_SCORE_BASE.getName()).getIntValue());
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_ADD_AURA_ITEM_ID.getName())){
                configTemp.setAddAuraItemId(activityConfigMap.get(eActivityConfigType.CARPTRIP_ADD_AURA_ITEM_ID.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_EXP_ITEM_ID.getName())){
                configTemp.setExpItemId(activityConfigMap.get(eActivityConfigType.CARPTRIP_EXP_ITEM_ID.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_AURA_ITEM_ID.getName())){
                configTemp.setAuraItemId(activityConfigMap.get(eActivityConfigType.CARPTRIP_AURA_ITEM_ID.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_STRENGTH_ITEM_ID.getName())){
                configTemp.setStrengthItemId(activityConfigMap.get(eActivityConfigType.CARPTRIP_STRENGTH_ITEM_ID.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_TOWER_MAX_FLOOR.getName())){
                configTemp.setTowerMaxFloor(activityConfigMap.get(eActivityConfigType.CARPTRIP_TOWER_MAX_FLOOR.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_DRAW_NOTICE_CONDITION.getName())){
                configTemp.setCARPTRIP_DRAW_NOTICE_CONDITION(activityConfigMap.get(eActivityConfigType.CARPTRIP_DRAW_NOTICE_CONDITION.getName()).getIntValue());
            }
            if(activityConfigMap.containsKey(eActivityConfigType.CARPTRIP_ROE_ITEM_ID.getName())){
                configTemp.setYuZiItemId(activityConfigMap.get(eActivityConfigType.CARPTRIP_ROE_ITEM_ID.getName()).getIntValue());
            }
            configTemp.setSkillUpNum(activityConfigMap.get(eActivityConfigType.CARPTRIP_TOWER_SKILL_UPNUM.getName()).getIntValue());

            //其他配置项
            configTemp.setDrawTenLimit(activityConfigMap.get(eActivityConfigType.CARPTRIP_TOWER_DRAW_TEN_LIMIT.getName()).getIntValue());
            configTemp.setDrawWeightList(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.CARPTRIP_DRAW_WEIGHT.getName()).getValue(), "\\|"));
            configTemp.setDRAW_ISBIG(activityConfigMap.get(eActivityConfigType.CARPTRIP_DRAW_ISBIG.getName()).getIntValue());
            configTemp.setDRAW_BIG_PRO(activityConfigMap.get(eActivityConfigType.CARPTRIP_DRAW_BIG_PRO.getName()).getIntValue());

            setBossRewardTempList(bossRewardTemps);
            configTemp.setTotalCellNum(totalCellNum);
            config = configTemp;
        }
        getLogger().info("reload CarpTrip Activity finish");

        // 在线玩家下发数据
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            CarpTripModule module = gamePlayer.getModule(CarpTripModule.class);
            module.syncConfig();
            module.initUserData();
            module.syncUserData();
            module.syncPveData();
        }
    }


    public static int getDrawUpLv(int drawExp, CarpTripConfig config) {
        CarpTripDrawUpInfo result;
        long allCost = 0;
        int index = 0;
        for (int i = 0; i < config.getDrawUpInfoList().size(); i++) {
            CarpTripDrawUpInfo drawUpInfo = config.getDrawUpInfoList().get(i);
            allCost += drawUpInfo.getExp();
            if(drawExp >= allCost){
                index++;
            }
        }
        if(index <= config.getDrawUpInfoList().size() - 1){
            result = config.getDrawUpInfoList().get(index);
        }else {
            result = config.getDrawUpInfoList().get(config.getDrawUpInfoList().size() - 1);
        }
        return result.getLevel();
    }

    public static boolean isSpecialGoods(int goodsId) {
        if(config == null){
            return false;
        }
        int[] goodsIdList = new int[]{ config.getAuraItemId(), config.getExpItemId(), config.getStrengthItemId()};
        for (int id : goodsIdList) {
            if(id == goodsId){
                return true;
            }
        }
        return false;
    }


    public static CarpTripCell getCell(int passId, int cell) {
        return config.getCell(passId, cell);
    }

    public static CarpTripCell getNextCell(int passId, int cell) {
        return config.getNextCell(passId, cell);
    }
    
    @Override
    public boolean stop() {
        return false;
    }


    public static CarpTripConfig getConfig() {
        return config;
    }

    public static void setConfig(CarpTripConfig config) {
        CarpTripMgr.config = config;
    }

    public static List<CarpTripProto.CarpTripBossRewardTemp> getBossRewardTempList() {
        return bossRewardTempList;
    }

    public static void setBossRewardTempList(List<CarpTripProto.CarpTripBossRewardTemp> bossRewardTempList) {
        CarpTripMgr.bossRewardTempList = bossRewardTempList;
    }

    public static int getActivityId(){
        if(getActivityInfo() == null){
            return 0;
        }
        return getActivityInfo().getActivityId();
    }
}
